package com.e5.training.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class AuthenticationFilter
 */
public class AuthenticationFilter implements Filter {

	private String loginUrl;

	/**
	 * Default constructor.
	 */
	public AuthenticationFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {


		// pass the request along the filter chain
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession httpSession = httpRequest.getSession();


		httpResponse.setHeader("Cache-Control", "no-cache");
		httpResponse.setHeader("Cache-Control", "no-store");
		httpResponse.setDateHeader("Expires", 0);
		httpResponse.setHeader("Pragma", "no-cache");

		String requestURL = httpRequest.getRequestURL().toString();
		boolean isHtml = requestURL.endsWith("/")||requestURL.endsWith(".html")||requestURL.endsWith(".css")||requestURL.endsWith(".js")||requestURL.contains("images")||requestURL.endsWith("login.jsp")||requestURL.endsWith("Login.action")||requestURL.endsWith("error.jsp");
		if(isHtml){
			chain.doFilter(request, response);
		}else if (httpSession.getAttribute("accountInfo") == null) {
			httpRequest.setAttribute("mes", "You have not signed in the website,please clik "+"<a href='login.jsp'>here</a>"+ " to  sign in first");
			httpRequest.getRequestDispatcher(loginUrl).forward(httpRequest,
					httpResponse);
		} else
			chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		loginUrl = fConfig.getInitParameter("loginUrl");
		if (loginUrl == null || "".equals(loginUrl)) {
			loginUrl = "login";
		}
	}
}
